<template>
  <div class="search-box">
    <div class="search-area" ref="searchArea" :style="{'flex-wrap': isCollapse ? 'nowrap' : 'wrap'}">
      <div class="search-item flex-1" v-for="(item,index) in configList" :key="index">
        <span  :style="labelStyle">{{item.label}}</span>
        <template v-if="item.type === 'select'">
          <el-select
              v-model="reactiveData.searchForm[item.field]"
              clearable
              :placeholder="item.placeholder || `请选择${item.label}`"
              :multiple="item.multiple === undefined ? true : item.multiple"
              collapse-tags>
            <template v-if="item.options && Array.isArray(item.options)">
              <el-option v-for="itemOp in item.options" :key="itemOp.value" :value="itemOp.value" :label="itemOp.label"></el-option>
            </template>
          </el-select>
        </template>
        <template v-else-if="item.type === 'input'">
          <el-input
              v-model="reactiveData.searchForm[item.field]"
              clearable
              :placeholder="item.placeholder || `请输入${item.label}`"
          ></el-input>
        </template>
        <template v-else-if="['daterange', 'datetimerange'].includes(item.type)">
          <el-date-picker
              v-model="reactiveData.searchForm[item.field]"
              :type="item.type"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
          ></el-date-picker>
        </template>
        <template v-else-if="item.type === 'inputrange'">
          <input-range v-model="reactiveData.searchForm[item.field]" clearable></input-range>
        </template>
        <template v-else-if="item.type === 'switch'">
          <el-switch
              v-model="reactiveData.searchForm[item.field]"
              :active-value="item.activeValue === undefined ? true : item.activeValue"
              :inactive-value="item.inactiveValue === undefined ? false : item.inactiveValue"
              :active-text="item.activeText"
              :inactive-text="item.inactiveText"/>
        </template>
      </div>
      <div class="btn-box">
        <el-button type="primary" @click="handleSearch">筛选</el-button>
        <el-button plain @click="resetForm">重置</el-button>
        <el-button v-if="isShowCollapse" text @click="handleCollapse">
          <span class="flex-box">
            {{isCollapse ? '展开' : '收起'}}
            <el-icon class="el-icon--right icon-arrow" :style="{transform: isCollapse ? 'rotate(0deg)' : 'rotate(180deg)'}">

            </el-icon>
          </span>
        </el-button>
      </div>
    </div>
    <div class="operate-box">
      <slot/>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, nextTick, computed, watch } from 'vue'
import {debounce, deepClone} from '@/utils'


/**
 * 使用说明
 * field: 字段名
 * type: select / input / daterange / datetimernage / inputrange / switch
 * defaultShow: 是否默认显示（在折叠状态下）
 * default: 默认值
 * multiple: 是否多选
 */

const props = defineProps({
  searchConfig: {
    type: Array,
    default: () => []
  },
  labelStyle: {
    type: Object,
    default: () => ({})
  }
})

const emits = defineEmits(['search'])

const reactiveData = reactive({
  searchForm: {}
})

const searchArea  = ref(null)
const configList = ref([])
const isCollapse = ref(true)
let cloneForm = {}

const isShowCollapse = computed(() => {
  if (isCollapse.value) {
    return props.searchConfig.length !== configList.value.length
  } else {
    return true
  }
})

const defaultList = computed(() => props.searchConfig.filter(item => item.defaultShow))

const shortcuts = [
  {
    text: '近七天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

window.onresize = debounce(() => {
  setSearchNumber()
}, 20)

function handleCollapse () {
  isCollapse.value = !isCollapse.value
  setSearchNumber()
}

function setSearchNumber () {
  configList.value = []
  // 获取 searchArea 宽度
  if (isCollapse.value) {
    nextTick(() => {
      // 如果是折叠状态
      if (searchArea.value) {
        const width = searchArea.value.clientWidth - 250
        let sumWidth = 0
        defaultList.value.forEach(item => {
          if (item.width && (sumWidth + item.width < width)) {
            configList.value.push(item)
            sumWidth += item.width
          }
        })
      }
    })
  } else {
    // 如果是展开状态
    configList.value = props.searchConfig
  }
}

function handleSearch () {
  emits('search', reactiveData.searchForm)
}

function resetForm () {
  reactiveData.searchForm = deepClone(cloneForm)
  handleSearch()
}

function init () {
  reactiveData.searchForm = {}
  props.searchConfig.forEach(item => {
    if (item.default !== undefined) {
      reactiveData.searchForm[item.field] = item.default
    }
    item.width = ['daterange', 'datetimerange'].includes(item.type) ? 480 : 240
  })
  cloneForm = deepClone(reactiveData.searchForm)
  setSearchNumber()
}

init()

watch(() => props.searchConfig, () => {
  init()
})

</script>

<style lang="scss" scoped>
.search-box{
  background: #fafafa;
  display: flex;
  .search-area{
    flex-grow: 1;
    display: flex;
    align-items: center;
    padding: 5px 10px;
    height: auto;
    overflow: hidden;
    .search-item{
      margin: 5px 10px;
      display: flex;
      align-items: center;
      & > span{
        width: 60px;
        text-align: right;
        margin-right: 10px;
        flex-shrink: 0;
        font-size: 14px;
        color: #333;
      }
      ::v-deep(.el-input__inner){
        width: 150px;
      }
      ::v-deep(.el-range-editor.el-input__inner){
        width: 390px;
      }
      ::v-deep(.el-switch) {
        height: 32px;
        width: 150px;
      }
    }
    .btn-box{
      flex-shrink: 0;
      margin-left: 20px;
      display: flex;
      align-items: center;
      .el-button{
        margin-right: 10px;
      }
      .icon-arrow{
        transition: transform .5s;
      }
    }
  }
  .operate-box{
    flex-shrink: 0;
    padding: 0 20px;
    margin: 10px;
  }
  .flex-box{
    display: flex;
    align-items: center;
  }
}
</style>
